﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using CloudSoft.Extensions;

namespace ERPStore.Exporter.Models.LeadSources
{
	public class CherchonsSource : ERPStore.Models.LeadSourceBase
	{
		public override string Id
		{
			get { return "127E8B0A-2FE6-4824-B762-43EF1FF6F8A6"; }
		}

		public override string Name
		{
			get { return "Cherchons"; }
		}

		public override string Description
		{
			get { return "Moteur de comparaison Cherchons.com (CPC)"; }
		}

		public override string TrackSourceId
		{
			get { return "cherchons.com"; }
		}

		public override string Medium
		{
			get { return "cpc"; }
		}

		public override ERPStore.Models.LeadSourceType LeadSourceType
		{
			get { return ERPStore.Models.LeadSourceType.PriceComparator; }
		}

		public override bool Match(Uri sourceUri, Uri landingUri, out string keywords, out string subHost, out decimal amount)
		{
			keywords = null; 

			subHost = "No referer";
			amount = 0.17m;
			var landingPrms = landingUri.GetParameters();

			if (landingPrms.AllKeys.Contains("gclid")) // Lien sponso 
			{
				return false;
			}
			else if (landingPrms.AllKeys.Contains("estid"))
			{
				var estid = landingPrms["estid"];
				if (estid.Equals(TrackSourceId, StringComparison.InvariantCultureIgnoreCase))
				{
					keywords = GetKeywords(sourceUri) ?? string.Empty; 
					if (sourceUri.GetParameters().AllKeys.Contains("http_referer"))
					{
						var url = sourceUri.GetParameters()["http_referer"];
						if (url != null)
						{
							url = System.Web.HttpUtility.UrlDecode(url);
							var uri = new Uri(url);
							var path = uri.LocalPath;
							if (path != null)
							{
								keywords = path.Replace(".html", "")
												.Replace("-", " ")
												.Replace("-", " ")
												.Replace("/r/", "");

								keywords = Uri.UnescapeDataString(keywords ?? string.Empty);
							}
						}
					}
					keywords = keywords.Replace("+", " ");

					return true;
				}
			}

			return false;
		}

		protected override string GetKeywords(Uri uri)
		{
			if (uri == null)
			{
				return null;
			}

			var prms = uri.GetParameters();

			var k = prms["parameter"] ?? prms["ms"] ?? string.Empty;

			return k.Trim().DefaultValueIfNullOrTrimmedEmpty(null);
		}

	}
}
